package dfs_bfs.test130;

/**
 * 被围绕的区域
 * @author code_yc
 * @version 1.0
 * @date 2020/7/8 11:27
 */
public class Solution1 {

    // DFS
    int r, c;

    // DFS
    public void solve(char[][] board) {
        if(board == null || board.length == 0 || board[0].length == 0) return;
        r = board.length;
        c = board[0].length;
        // 遍历边界
        for(int i = 0; i < r; i++){
            if(board[i][0] == 'O') dfs(board, i, 0);
            if(board[i][c - 1] == 'O') dfs(board, i, c - 1);
        }
        for(int j = 0; j < c; j++){
            if(board[0][j] == 'O') dfs(board, 0, j);
            if(board[r - 1][j] == 'O') dfs(board, r - 1, j);
        }
        // 更新数组
        for(int i = 0; i < r; i++){
            for(int j = 0; j < c; j++){
                if(board[i][j] == 'X') continue;
                if(board[i][j] == 'O') board[i][j] = 'X';
                if(board[i][j] == 'Y') board[i][j] = 'O';
            }
        }
    }

    // dfs
    private void dfs(char[][] board, int i, int j){
        board[i][j] = 'Y';
        int[] dx = {-1, 0, 1, 0};
        int[] dy = {0, 1, 0, -1};
        for(int k = 0; k < 4; k++){
            int x = i + dx[k], y = j + dy[k];
            if(x >= 0 && x < r && y >= 0 && y < c && board[x][y] == 'O'){
                dfs(board, x, y);
            }
        }
    }
}
